package ynu.edu.online_course.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ynu.edu.online_course.entity.WatchRecord;
import ynu.edu.online_course.mapper.WatchRecordMapper;
import ynu.edu.online_course.service.WatchRecordService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WatchRecordServiceImpl implements WatchRecordService {

    @Autowired
    private WatchRecordMapper watchRecordMapper;

    @Override
    public void addWatchRecord(WatchRecord watchRecord) {
        watchRecordMapper.insertWatchRecord(watchRecord);
    }

    @Override
    public Long getTotalWatchDuration(Long userId) {
        return watchRecordMapper.getTotalWatchDurationByUserId(userId);
    }

    @Override
    public List<WatchRecord> getUserWatchRecords(Long userId) {
        return watchRecordMapper.findByUserId(userId);
    }
    @Autowired
    public WatchRecordServiceImpl(WatchRecordMapper watchRecordMapper) {
        this.watchRecordMapper = watchRecordMapper;
    }

    @Override
    public Map<Long, Long> getChapterWatchDurations() {
        List<Map<String, Object>> chapterDurations = watchRecordMapper.getChapterWatchDurations();
        Map<Long, Long> result = new HashMap<>();
        for (Map<String, Object> entry : chapterDurations) {
            Long chapterId = ((Number) entry.get("chapter_id")).longValue();
            Long duration = ((Number) entry.get("total_duration")).longValue();
            result.put(chapterId, duration);
        }
        return result;
    }

    @Override
    public Map<Long, Long> getCourseWatchDurations() {
        List<Map<String, Object>> courseDurations = watchRecordMapper.getCourseWatchDurations();
        Map<Long, Long> result = new HashMap<>();
        for (Map<String, Object> entry : courseDurations) {
            Long courseId = ((Number) entry.get("courseId")).longValue();
            Long duration = ((Number) entry.get("totalDuration")).longValue();
            result.put(courseId, duration);
        }
        return result;
    }
}
